package top.deepdesigner.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * shiro权限会话管理
 */
public class AdminWebSessionManager extends DefaultWebSessionManager {

  public static final String LOGIN_TOKEN_KEY = "X-Dts-Admin-Token";
  private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

  @Override
  protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
    String id = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY);
    if (!StringUtils.isEmpty(id)) {
      //判读请求头中是否有id，如果拥有 表示Vue 异步
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
      return id;
    } else {
      //没有，相当于前端是jsp页面 同步
      return super.getSessionId(request, response);
    }
  }
}